package com.hdu.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.hostlist}")
    private String hostlist;

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 1. 创建底层 REST 客户端
        RestClient restClient = RestClient.builder(
                new HttpHost(hostlist.split(":")[0], Integer.parseInt(hostlist.split(":")[1]), "http")
        ).build();

        // 2. 创建 Jackson 映射器
        JacksonJsonpMapper jsonpMapper = new JacksonJsonpMapper(new ObjectMapper());

        // 3. 创建传输层适配器
        ElasticsearchTransport transport = new RestClientTransport(
                restClient,
                jsonpMapper
        );

        // 4. 创建 ElasticsearchClient 实例
        return new ElasticsearchClient(transport);
    }
}